package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RequestMapping("/order")
@RestController
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderServicel;

   @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
       //首先得到前台传递过来的验证码
       String validateCode = (String) map.get("validateCode");
       //得到前台传递过来的手机号，用来验证验证码
       String telephone = (String) map.get("telephone");
       //得到自己保存的验证码
       String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
       //进行比对
       if(validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
           //设置预约类型
           map.put("orderType", Order.ORDERTYPE_WEIXIN);
           Result result = null;
           try {
               result = orderServicel.order(map);
           }catch (Exception e){
               e.printStackTrace();
               return result;
           }
           //如果预约成功，发送成功的短信给用户
           if(result.isFlag()){
               try {
                   SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String) map.get("orderDate"));
               } catch (ClientException e) {
                   e.printStackTrace();
               }
           }
           return result;
       }else {
           return new Result(false , MessageConstant.VALIDATECODE_ERROR);
       }
    }

    //根据预约的id去预约信息表中查询预约信息
    @RequestMapping("/findById")
    public Result add(Integer id){
       try {
           Map map = orderServicel.findById(id);
           return new Result(true , MessageConstant.QUERY_ORDER_SUCCESS , map);
       }catch (Exception e){
           e.printStackTrace();
           return new Result(false , MessageConstant.QUERY_ORDER_FAIL);
       }
    }
}
